<template>
  <!-- // 分配角色 -->
  <div>
    <el-tree
      ref="refTree"
      :data="permissionsList"
      :props="{label:'name'}"
      default-expand-all
      :show-checkbox="true"
      :check-strictly="true"
      node-key="id"
    />
    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="hSubmit">确定</el-button>
      <el-button @click="hClose">取消</el-button>
    </div>
  </div>
</template>
<script>
import { getPermissionList } from '@/api/permissions'
import { tranListToTreeData } from '@/utils'
import { getRoleDetail, assignPerm } from '@/api/settings'
export default {
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      permissionsList: [], //  存储权限信息
      permIds: [] // 当前角色已有的权限

    }
  },
  created() {
    this.loadPermissionList()
    // 调用接口，获取当前这个角色已经具备的权限
    this.loadPermissionByRoleId()
  },
  methods: {
    hSubmit() {
    //   this.$emit('close')
      this.doSave()
    },
    hClose() {
      this.$emit('close')
    },

    // 获取所有权限点信息
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        // console.log(res)
        // 将数据转换成树形结构
        this.permissionsList = tranListToTreeData(res.data)
        // console.log(this.permissionsList)
      } catch (error) {
        console.log(error)
      }
    },

    // 根据roleId获取当前这个角色已经具备的权限
    async loadPermissionByRoleId() {
      try {
        // 根据roleId获取当前这个角色已经具备的权限
        const res = await getRoleDetail(this.roleId)
        console.log('获取当前角色的已有的权限点数据', res.data.permIds)
        // 回填
        this.$refs.refTree.setCheckedKeys(res.data.permIds)
      } catch (error) {
        console.log(error)
      }
    },

    async doSave() {
      try {
        // 获取选中的权限点
        const permIds = this.$refs.refTree.getCheckedKeys()
        const res = await assignPerm({ id: this.roleId, permIds: permIds })
        console.log(res)
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
